<template>
  <view class="update-container">
    <view class="form-section">
      <view class="form-item">
        <view class="info-label">负责人</view>
        <input class="form-input" v-model="formData.name" placeholder="请输入负责人姓名" />
      </view>
      
      <view class="form-item">
        <view class="info-label">身份证号码</view>
        <input class="form-input" v-model="formData.idCardNumber" placeholder="请输入身份证号码" />
      </view>
      
      <view class="form-item">
        <view class="info-label">手机号</view>
        <input class="form-input" v-model="formData.phoneNumber" placeholder="请输入手机号" />
      </view>
      
      <view class="form-item">
        <view class="info-label">验证码</view>
        <view class="verification-container">
          <input class="form-input verification-input" v-model="verificationCode" placeholder="输入验证码" />
          <button class="verification-btn" @click="getVerificationCode" :disabled="countingDown">{{ verificationBtnText }}</button>
        </view>
      </view>
      
      <view class="form-item">
        <view class="info-label">店名</view>
        <input class="form-input" v-model="formData.storeName" placeholder="请输入店名" />
      </view>
      
      <view class="form-item">
        <view class="info-label">工商营业执照号码</view>
        <input class="form-input" v-model="formData.licenseNumber" placeholder="请输入营业执照号码" />
      </view>
      
      <view class="form-item">
        <view class="info-label">经营区域</view>
        <picker class="form-picker" mode="region" bindchange="bindRegionChange" value="{{ region }}">
          <view class="picker-content">
            {{ region[0] }} {{ region[1] }} {{ region[2] }}
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <view class="info-label">地址</view>
        <input class="form-input" v-model="formData.address" placeholder="请输入详细地址" />
      </view>
      
      <view class="form-item">
        <view class="info-label">商家介绍</view>
        <textarea class="form-textarea" v-model="formData.description" placeholder="请输入商家介绍" />
      </view>
    </view>
    
    <view class="image-section">
      <view class="image-group">
        <view class="info-label">身份证正反面照片</view>
        <view class="image-upload-container">
          <view v-for="(image, index) in idCardImages" :key="index" class="image-item">
            <image :src="image" class="uploaded-image"></image>
            <view class="delete-btn" @click="deleteImage('idCard', index)">删除</view>
          </view>
          <view class="upload-btn" @click="uploadImage('idCard')" v-if="idCardImages.length < 2">
            <text>+</text>
          </view>
        </view>
      </view>
      
      <view class="image-group">
        <view class="info-label">营业执照</view>
        <view class="image-upload-container">
          <view v-for="(image, index) in licenseImages" :key="index" class="image-item">
            <image :src="image" class="uploaded-image"></image>
            <view class="delete-btn" @click="deleteImage('license', index)">删除</view>
          </view>
          <view class="upload-btn" @click="uploadImage('license')" v-if="licenseImages.length < 1">
            <text>+</text>
          </view>
        </view>
      </view>
      
      <view class="image-group">
        <view class="info-label">门面照片</view>
        <view class="image-upload-container">
          <view v-for="(image, index) in storeImages" :key="index" class="image-item">
            <image :src="image" class="uploaded-image"></image>
            <view class="delete-btn" @click="deleteImage('store', index)">删除</view>
          </view>
          <view class="upload-btn" @click="uploadImage('store')">
            <text>+</text>
          </view>
        </view>
      </view>
    </view>
    
    <view class="action-section">
      <button class="save-button" @click="handleSave">保存</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

// 默认表单数据，确保页面初次加载时有内容
const formData = ref({
  name: '张三',
  idCardNumber: '40365236541232563',
  phoneNumber: '18893039203',
  storeName: '店小二',
  licenseNumber: '4252336467474764646',
  businessArea: '焦作市山阳区',
  address: '山阳区迎宾路32号',
  description: '商家介绍商家介绍商家介绍商家介绍商家介绍商家介绍商家介绍商家介绍商家介绍商家介绍商家介绍'
});

// 验证码相关
const verificationCode = ref('');
const countingDown = ref(false);
const countdown = ref(60);
const verificationBtnText = ref('获取验证码');

// 区域选择
const region = ref(['河南省', '焦作市', '山阳区']);

// 图片数据
const idCardImages = ref<string[]>([]);
const licenseImages = ref<string[]>([]);
const storeImages = ref<string[]>([]);

// 组件挂载时初始化数据
onMounted(() => {
  try {
    // 这里可以从API获取商户数据，现在使用模拟数据
    // 如果需要从store获取数据，可以在这里添加
    // const merchantInfo = store.state.merchant?.merchantInfo || {};
    // if (Object.keys(merchantInfo).length > 0) {
    //   formData.value = { ...formData.value, ...merchantInfo };
    // }
    
    // 初始化模拟图片数据
    const mockImageUrl = 'https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?ixlib=rb-4.0.3&auto=format&fit=crop&w=100&q=80';
    idCardImages.value = [mockImageUrl, mockImageUrl];
    licenseImages.value = [mockImageUrl];
    storeImages.value = [mockImageUrl];
  } catch (error) {
    console.log('初始化商户数据失败:', error);
  }
});

// 绑定区域选择
const bindRegionChange = (e: any) => {
  region.value = e.detail.value;
  formData.value.businessArea = region.value.join(' ');
};

// 获取验证码
const getVerificationCode = () => {
  if (!formData.value.phoneNumber) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    });
    return;
  }
  
  // 模拟发送验证码
  uni.showToast({
    title: '验证码已发送',
    icon: 'success'
  });
  
  // 开始倒计时
  countingDown.value = true;
  verificationBtnText.value = `${countdown.value}秒后重新获取`;
  
  const timer = setInterval(() => {
    countdown.value--;
    verificationBtnText.value = `${countdown.value}秒后重新获取`;
    
    if (countdown.value <= 0) {
      clearInterval(timer);
      countingDown.value = false;
      countdown.value = 60;
      verificationBtnText.value = '获取验证码';
    }
  }, 1000);
};

// 定义图片类型的联合类型
type ImageType = 'idCard' | 'license' | 'store';

// 上传图片
const uploadImage = (type: ImageType) => {
  uni.chooseImage({
    count: type === 'idCard' ? 2 - idCardImages.value.length : 9,
    success: (res: UniApp.ChooseImageSuccessCallbackResult) => {
      // 确保tempFilePaths总是数组类型
      const tempFilePaths: string[] = Array.isArray(res.tempFilePaths) ? res.tempFilePaths : [res.tempFilePaths];
      
      // 模拟上传，实际应该调用上传API
      tempFilePaths.forEach((path: string) => {
        if (type === 'idCard') {
          idCardImages.value.push(path);
        } else if (type === 'license') {
          licenseImages.value.push(path);
        } else if (type === 'store') {
          storeImages.value.push(path);
        }
      });
    }
  });
};

// 删除图片
const deleteImage = (type: ImageType, index: number) => {
  if (type === 'idCard') {
    idCardImages.value.splice(index, 1);
  } else if (type === 'license') {
    licenseImages.value.splice(index, 1);
  } else if (type === 'store') {
    storeImages.value.splice(index, 1);
  }
};

// 保存数据
const handleSave = () => {
  // 表单验证
  if (!formData.value.name) {
    uni.showToast({
      title: '请输入负责人姓名',
      icon: 'none'
    });
    return;
  }
  
  // 模拟保存数据
  uni.showLoading({
    title: '保存中...'
  });
  
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    });
    
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }, 1000);
};
</script>

<style scoped>
.update-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 15rpx;
  margin-bottom: 10rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.form-item:last-child {
  border-bottom: none;
}

.info-label {
  width: 220rpx;
  font-size: 28rpx;
  color: #666;
  margin-right: 40rpx;
}

.form-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  height: 80rpx;
}

.verification-container {
  flex: 1;
  display: flex;
  align-items: center;
}

.verification-input {
  flex: 1;
  margin-right: 20rpx;
}

.verification-btn {
  font-size: 24rpx;
  color: #007aff;
  background-color: transparent;
  padding: 0 20rpx;
  height: 60rpx;
  line-height: 60rpx;
}

.form-picker {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.picker-content {
  padding: 20rpx 0;
}

.form-textarea {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  min-height: 140rpx;
  line-height: 40rpx;
  padding: 15rpx 0;
}

.image-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 15rpx;
  margin-bottom: 20rpx;
}

.image-group {
  margin-bottom: 20rpx;
}

.image-group:last-child {
  margin-bottom: 0;
}

.image-upload-container {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
  margin-left: 260rpx;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 24rpx;
  padding: 8rpx 0;
  border-radius: 0 0 8rpx 8rpx;
}

.upload-btn {
  width: 200rpx;
  height: 200rpx;
  border: 1rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 60rpx;
}

.action-section {
  padding: 0 20rpx 20rpx;
}

.save-button {
  background-color: #007aff;
  color: #fff;
  border-radius: 8rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
}

.save-button:active {
  opacity: 0.8;
}
</style>